import json
import time
import uuid
from datetime import datetime

from django.contrib.auth.models import User
from django.contrib import auth
from django.http import JsonResponse
from django.shortcuts import redirect, render, HttpResponse
from django.urls import reverse
from . import models
from .module.DataStructure import uuidSet
from .module.severPublish import MQTTClient
from .views import jsonResponse, Checker


def controlboard(request):
    if not request.session.get('islogin'):
        return HttpResponse(jsonResponse(500, '你尚未登录', None).getJson())
    return render(request, 'userdeviceinfo.html')


def deviceInfo(request):
    isLogin = request.session.get('islogin')
    if not isLogin:
        return HttpResponse(jsonResponse(500, '你尚未登录', None).getJson())
    requestInfo = Checker(request.read()).checkandgetjson()
    if not requestInfo:
        return HttpResponse(jsonResponse(500, '不合法的请求', None).getJson())
    device = models.Device.objects.filter(user_name=requestInfo['username'])
    res = list(device.values('device_id', 'gateway_num', 'user_name', 'device_name', 'description', 'status'))
    return HttpResponse(jsonResponse(0, '', res).makeDicAndGetJson())


def deviceRunningInfo(request):
    if not request.session.get('islogin'):
        return HttpResponse(jsonResponse(500, '你尚未登录', None).getJson())
    requestInfo = Checker(request.read()).checkandgetjson()
    if not requestInfo:
        return HttpResponse(jsonResponse(500, '不合法的请求', None).getJson())
    deviceRunInfo = models.DeviceRunningInfo.objects.filter(device_name=requestInfo['devicename'])
    dataList = list(deviceRunInfo.values('device_name', 'device_running_info', 'time_stamp'))
    return HttpResponse(jsonResponse(0, '', dataList).makeDicAndGetJson())


def addDevice(request):
    if request.method == 'GET':
        return HttpResponse(jsonResponse(0, '', None).getJson())
    if not request.session.get('islogin'):
        return HttpResponse(jsonResponse(500, '你尚未登录', None).getJson())
    requestInfo = Checker(request.read()).checkandgetjson()
    if not requestInfo:
        return HttpResponse(jsonResponse(500, '不合法的请求', None).getJson())
    # 输入字段验证
    gatewayNum = requestInfo['gatewayNum']
    userName = request.session.get('username')
    if len(gatewayNum) < 0:
        return HttpResponse(jsonResponse(500, '不合法的请求', None).getJson())
    # 业务逻辑
    # TODO finish add the device
    gatewayDic = dict()
    gatewayDic['option'] = 'getdevicecontent'
    msgUUID = uuid.uuid1()
    gatewayDic['msgUUID'] = msgUUID
    uuidSet.add(msgUUID)
    MQTTClient.publish(gatewayNum, json.dumps(gatewayDic))
    return HttpResponse(jsonResponse(0, '请求发送成功', None).getJson())


def getDeviceKinds(request):
    # if not request.session.get('islogin'):
    #     return HttpResponse(jsonResponse(500, '你尚未登录', None).getJson())
    deviceKinds = models.DeviceKind.objects.all()
    dataList = list(deviceKinds.values())
    return HttpResponse(jsonResponse(0, '', dataList).makeDicAndGetJson())


def delDevice(request):
    if not request.session.get('islogin'):
        return HttpResponse(jsonResponse(500, '你尚未登录', None).getJson())
    requestInfo = Checker(request.read()).checkandgetjson()
    if not requestInfo:
        return HttpResponse(jsonResponse(500, '不合法的请求', None).getJson())
    # 判断是否存在设备
    device = models.Device.objects.filter(device_id=requestInfo['deviceID'])
    if not device:
        return HttpResponse(jsonResponse(500, '不存在该设备', None).getJson())
    # 判断是否本人进行删除
    if device.user_name != request.session.get('username'):
        return HttpResponse(jsonResponse(500, "你没有权限", None).getJson())
    models.DeviceRunningInfo.objects.filter(device_id=device.device_id).delete()
    judge = device.delete()
    if judge[0] == 0:  # 判断是否操作成功
        return HttpResponse(jsonResponse(500, '操作失败', None).getJson())
    return HttpResponse(jsonResponse(0, '操作成功', None).getJson())


def postMessageToDevice(request):
    if not request.session.get('islogin'):
        return HttpResponse(jsonResponse(500, '你尚未登录', None).getJson())
    requestInfo = Checker(request.read()).checkandgetjson()
    if not requestInfo:
        return HttpResponse(jsonResponse(500, '不合法的请求', None).getJson())
    # device = models.Device.objects.filter(device_id=requestInfo['deviceID'])
    # if not device:
    #     return HttpResponse(jsonResponse(500, '不存在该设备', None).getJson())
    MQTTClient.publish(requestInfo['gatewaynum'], request.read())
    return HttpResponse(jsonResponse(0, '', None).getJson())


def test(request):
    info = models.AuthUser.objects.all()
    MQTTClient.publish('test', 'this is a message')
    # deviceKind = models.DeviceKind.objects.get(kind_id=1)
    # device = models.Device(device_id=1, device_name='hahaha', kind=deviceKind, user_name='root', joined_time=datetime.now())
    # device.save()

    # delect = models.Device.objects.get(user_name='root')
    # result = delect.delete()
    # print(type(result))
    # print(result)
    # return HttpResponse(jsonResponse(0, '', result).makeDicAndGetJson())
